﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using API;
using CoreGraphics;
using Foundation;
using mb;
using mb.iOS;
using Masonry;
using MyExtensions;
using UIKit;
using static libmp.DataStore;
using System.Linq;

namespace libmp
{
    public class VCCategory : UINavigationController
    {
        static ILog logger = App.logger;

        public VCCategory()
        {
            TabBarItem = new UITabBarItem("分类", null, 0);
            NavigationBarHidden = true;
            PushViewController(new VCCategoryMain(), false);

        }
        public void ReClick()
        {
            logger.Log("reclick");
            if (ViewControllers.Length > 1)
            {
                PopViewController(false);
            }
        }
    }

    class VCCategoryMain : VCBaseInsertableList<VideoCategory>
    {
        static ILog logger = App.logger;
        UIView titleBar;
        int HeaderHeight = 48;
        List<InsertItem> insertItems = new List<InsertItem>();

        public override void ViewDidLoad()
        {
            var bkView = new UIView() { BackgroundColor = Util.MainBKColor };
            bkView.SetParent(View).MakeConstraints(m =>
            {
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Left.Right.Bottom.EqualTo(View);
            });
            base.ViewDidLoad();
            //View.BackgroundColor = UIColor.FromRGB(238, 238, 238);

            logger.Log("User.me.id:------->" + User.me.id);

            SetTitleBar("分类", View);
            CreateInsertViews();

            // listView.BackgroundColor = UIColor.Red;
            listView.Bounces = false;
            listView.RemakeConstraints(m =>
            {
                m.Left.Right.EqualTo(View);
                m.Top.EqualTo(titleBar.Bottom());
                m.Bottom.EqualTo(this.BottomLayoutGuideTop());
            });

            this.dataSource = DataStore.store.GetVideoCategory();
            this.Reload();
        }

        protected override int[] GetInsertIndex() => insertItems.Select(v => v.insertBefore).ToArray();
        protected override InsertItem GetInsertViewConfig(int idx) { return insertItems[idx]; }

        void SetTitleBar(string titleName, UIView View)
        {
            titleBar = new UIView()
            {
                BackgroundColor = Util.MainColor,
            };
            titleBar.SetParent(View);
            titleBar.Frame = new CGRect(0, 0, View.Frame.Size.Width, HeaderHeight);
            titleBar.MakeConstraints(m =>
            {
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Width.Left.EqualTo(View);
                m.Height.EqualTo(NSObject.FromObject(HeaderHeight));
            });
            var titleNameLabel = new UILabel();
            titleNameLabel.Text = titleName;
            titleNameLabel.SetParent(titleBar);
            titleNameLabel.MakeConstraints(m =>
            {
                m.Center.EqualTo(titleBar);
            });
            titleNameLabel.TextColor = UIColor.White;
            titleNameLabel.Font = UIFont.SystemFontOfSize(18f, 1.0f);
        }

        void CreateInsertViews()
        {
            //构建搜索框
            float Width = (float) View.Bounds.Width - 60;
            string placeholder = "手办模玩、展览演出";
            var textUIcolor = UIColor.FromRGB(93, 93, 93);
            var backgroundColor = UIColor.White;
            var clearImg = UIImage.FromFile($"{App.HotStorageRoot}/res/search/Close_02.png");
            var leftAskImg = UIImage.FromFile($"{App.HotStorageRoot}/res/search/ask_02.png");
            var textFont = UIFont.SystemFontOfSize(14);

            var insertView1 = new UIView();
            //insertView1.BackgroundColor = UIColor.Green.ColorWithAlpha(0.5f);
            insertItems.Add(new InsertItem()
            {
                insertBefore = 0,
                    view = insertView1,
                    height = 60,
                    stickyHeight = 60,
                    overwrite = false,
            });

            UISearchBar searchBar = Util.createMySearchBar(Width, placeholder, textUIcolor, clearImg, leftAskImg, textFont, backgroundColor);
            searchBar.SetParent(insertView1);
            searchBar.Frame = new RectangleF(10, 10, Width, 40);
            searchBar.Layer.CornerRadius = 20;
            searchBar.Layer.MasksToBounds = true;
            searchBar.SearchButtonClicked += (s, e) =>
            {
                logger.Log("search click", searchBar.Text);
            };

            var operationImageViewButton = new UIImageView();
            var imgoperationOne = UIImage.FromFile($"{App.HotStorageRoot}/res/category/Shaixuan.png");
            operationImageViewButton.Image = new UIImage(imgoperationOne.CGImage, 2, UIImageOrientation.Up);
            operationImageViewButton.SetParent(insertView1);
            operationImageViewButton.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(insertView1.CenterY());
                m.Left.EqualTo(NSObject.FromObject(Width + 20));
                m.Height.EqualTo(NSObject.FromObject(30));
                m.Width.EqualTo(NSObject.FromObject(30));
            });

            //广告框
            var insertView2 = new UIView();
            insertItems.Add(new InsertItem()
            {
                insertBefore = 0,
                    view = insertView2,
                    height = 140,
                    stickyHeight = 0,
            });

            var adveriseView = new UIView();
            adveriseView.SetParent(insertView2);
            adveriseView.MakeConstraints(m =>
            {
                m.Top.EqualTo(insertView2);
                m.Bottom.EqualTo(insertView2);
                m.Left.EqualTo(NSObject.FromObject(10));
                m.Width.EqualTo(NSObject.FromObject(View.Bounds.Width - 20));
            });
            adveriseView.Layer.CornerRadius = 6;
            adveriseView.Layer.MasksToBounds = true;
            // adveriseView.BackgroundColor = Util.MainColor;

            var adImg = libmp.DataStore.store.onlineConfig.AdImages[0];
            var imgView = new UIImageView();
            // mb.iOS.Util.SetUIImageViewUrl(imgView, adImg.imgpath);
            imgView.SetParent(adveriseView);
            imgView.MakeConstraints(m =>
            {
                m.Top.EqualTo(adveriseView);
                m.Bottom.EqualTo(adveriseView);
                m.Left.EqualTo(adveriseView);
                m.Width.EqualTo(NSObject.FromObject(View.Bounds.Width - 20));
            });
        }

        protected override CGSize GetItemsSize(int sec, int idx)
        {
            var w = View.Bounds.Width;
            var sd = sections[sec];
            if (sd.IsInsertView())
            {
                return new CGSize(w, sd.insertViewHeight);
            }
            else
            {
                return new CGSize(w / 2 - 1, (w / 2 - 1) / 2);
            }
        }

        protected class CategoryCellData : MyCellData
        {
            // public UIImageView imageView;
            public CategoryCellData(MyCollectionViewCell cell) : base(cell)
            {
                // var imageView = new UIImageView();
                // imageView.SetParent(cell);
                // imageView.Frame = new CGRect(0, 0, cell.Bounds.Width, cell.Bounds.Height);
                labTitle.RemakeConstraints(m =>
                {
                    m.Edges.EqualTo(cell).With.Insets(new UIEdgeInsets(10, 10, 0, 10));
                });
                labTitle.TextAlignment = UITextAlignment.Center;
                labTitle.BackgroundColor = UIColor.White;
                labTitle.Layer.CornerRadius = 6;
                labTitle.Layer.BorderWidth = 1;
                labTitle.Layer.BorderColor = new CGColor(0.7f, 0.7f, 0.7f, 1f);
                labTitle.ClipsToBounds = true;
            }
        }
        protected override MyCellData CreateCellData(MyCollectionViewCell cell, SectionData sd) => new CategoryCellData(cell);

        protected void UpdateCell(MyCollectionViewCell cell, int sec, int idx)
        {
            var sd = sections[sec];
            var cd = cell.data as CategoryCellData;
            cd.labTitle.Hidden = sd.IsInsertView();
            if (sd.IsInsertView()) { }
            else
            {
                var data = dataSource[sd.dataStartIndex + idx];
                cd.labTitle.Text = $"{data.catename}";
            }
        }
        protected override void OnItemSelected(int sec, int idx)
        {
            logger.Log("click", sec, idx);
            if (sec > 1)
            {
                var data = dataSource[idx];
                var nav = (UINavigationController) ParentViewController;
                nav.PushViewController(new VCCategoryMovieList(data.vcateid, idx), true);
            }
            else if (sec == 1)
            {
                //点击广告
                // var adImg = libmp.DataStore.store.onlineConfig.adImages[0];
                // logger.Log("点击====>" + adImg.imgid);
                // Xamarin.Essentials.Browser.OpenAsync(adImg.imghref, Xamarin.Essentials.BrowserLaunchMode.External);
                // User.me.Notify("clickad", LitJson.JsonMapper.ToJson(new { imgid = adImg.imgid }));
            }
        }
    }

    class VCCategoryMovieList : VCExMovieList
    {
        static ILog logger = App.logger;
        UIView titleBar;
        int HeaderHeight = 48;
        UILabel titleNameLabel;
        int categoryId;
        int selectIdx;

        public VCCategoryMovieList(int categoryId, int selectIdx)
        {
            this.categoryId = categoryId;
            this.selectIdx = selectIdx;
        }

        public override void ViewDidLoad()
        {
            var bkView = new UIView() { BackgroundColor = Util.MainBKColor };
            bkView.SetParent(View).MakeConstraints(m =>
            {
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Left.Right.Bottom.EqualTo(View);
            });
            base.ViewDidLoad();

            SetTitleBar(DataStore.store.GetVideoCategory() [this.selectIdx].catename);

            listView.RemakeConstraints(m =>
            {
                m.Left.Right.EqualTo(View);
                m.Top.EqualTo(this.TopLayoutGuideBottom()).Offset(HeaderHeight);
                m.Bottom.EqualTo(this.BottomLayoutGuideTop());
            });

            this.dataSource = DataStore.store.GetVideoForCateID(this.categoryId);
            this.Reload();
        }

        void SetTitleBar(string titleName)
        {
            titleBar = new UIView()
            {
                BackgroundColor = Util.MainColor,
            };
            titleBar.SetParent(View);
            titleBar.Frame = new CGRect(0, 0, View.Frame.Size.Width, 48);
            titleBar.MakeConstraints(m =>
            {
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Width.Left.EqualTo(View);
                m.Height.EqualTo(NSObject.FromObject(HeaderHeight));
            });
            // titleNameLabel = new UILabel();
            // titleNameLabel.Text = titleName;
            // titleNameLabel.SetParent(titleBar);
            // titleNameLabel.MakeConstraints(m =>
            // {
            //     m.Center.EqualTo(titleBar);
            // });
            // titleNameLabel.TextColor = UIColor.White;
            // titleNameLabel.Font = UIFont.SystemFontOfSize(18f, 1.0f);

            var btnPicWidth = 15;
            var btnPicHeight = 15;

            var topBarLeftView = new UIView();
            topBarLeftView.SetParent(titleBar);
            topBarLeftView.MakeConstraints(m =>
            {
                m.Left.EqualTo(NSObject.FromObject(10));
                m.Top.EqualTo(titleBar);
                m.Bottom.EqualTo(titleBar);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });

            var leftButton1 = new UIButton();
            leftButton1.Frame = new CGRect(0, 14, btnPicWidth + 30, btnPicHeight + 5);
            leftButton1.SetParent(topBarLeftView);
            var leftButton1ImageView = new UIImageView();
            var imgoperationArrow1 = UIImage.FromFile($"{App.HotStorageRoot}/res/user/Fanhui.png");
            leftButton1ImageView.Image = new UIImage(imgoperationArrow1.CGImage, 2, UIImageOrientation.Up);
            leftButton1ImageView.SetParent(leftButton1);
            leftButton1ImageView.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(leftButton1.CenterY());
                m.Left.EqualTo(NSObject.FromObject(5));
                m.Height.EqualTo(NSObject.FromObject(btnPicHeight));
                m.Width.EqualTo(NSObject.FromObject(btnPicWidth / 2));
            });
            var leftButton2Label = new UILabel();
            leftButton2Label.Text = "返回";
            leftButton2Label.Font = UIFont.SystemFontOfSize(12);
            leftButton2Label.SetParent(leftButton1);
            leftButton2Label.TextColor = UIColor.White;
            leftButton2Label.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(leftButton1.CenterY());
                m.Left.EqualTo(NSObject.FromObject(20));
                m.Height.EqualTo(NSObject.FromObject(btnPicHeight));
                m.Width.EqualTo(NSObject.FromObject(btnPicWidth + 20));
            });
            leftButton1.TouchUpInside += (s, e) =>
            {
                logger.Log("返回====>");
                var nav = (UINavigationController) ParentViewController;
                nav.PopViewController(false);
            };

            var topBarMiddleView = new UIView();
            topBarMiddleView.SetParent(titleBar);
            topBarMiddleView.MakeConstraints(m =>
            {
                m.Left.EqualTo(topBarLeftView.Right());
                m.Top.EqualTo(titleBar);
                m.Bottom.EqualTo(titleBar);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });

            var middleLabel = new UILabel();
            middleLabel.Text = titleName;
            middleLabel.Font = UIFont.BoldSystemFontOfSize(18);
            middleLabel.SetParent(topBarMiddleView);
            middleLabel.TextColor = UIColor.White;
            middleLabel.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(topBarMiddleView.CenterY());
                m.CenterX.EqualTo(topBarMiddleView.CenterX());
            });

            var topBarRightView = new UIView();
            topBarRightView.SetParent(titleBar);
            topBarRightView.MakeConstraints(m =>
            {
                m.Left.EqualTo(topBarMiddleView.Right());
                m.Top.EqualTo(titleBar);
                m.Bottom.EqualTo(titleBar);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });
        }

    }
}